-- 自动宠物赠送系统
-- 基于 Grow-a-Garden 游戏的 ProximityPrompt 机制

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local RunService = game:GetService("RunService")

local LocalPlayer = Players.LocalPlayer

local config = {
	targetPlayer = "lamb199303",
	petSlot = 5,              -- 宠物槽位
	tradeDistance = 10,        -- 交易距离
	holdDurationPadding = 0.1, -- 额外按住时间
	autoAcceptOnReceiver = true, -- 接收端自动接受
}

local function log(msg)
	print("[AutoPetGift] " .. msg)
	local ok = pcall(function()
		appendfile("auto_pet_gift_log.txt", "[AutoPetGift] " .. msg .. "\n")
	end)
	if not ok then
		pcall(function()
			writefile("auto_pet_gift_log.txt", "[AutoPetGift] " .. msg .. "\n")
		end)
	end
end

-- 获取目标玩家
local function getTarget()
	return Players:FindFirstChild(config.targetPlayer) or Players:GetPlayers()[2]
end

-- 移动到目标附近
local function moveNear(target)
	if not (LocalPlayer.Character and target and target.Character) then return false end
	local myHum = LocalPlayer.Character:FindFirstChildOfClass("Humanoid")
	local root = target.Character:FindFirstChild("HumanoidRootPart")
	if not (myHum and root) then return false end
	
	log("正在移动到目标附近...")
	myHum:MoveTo(root.Position)
	
	local tries = 0
	while tries < 40 do
		tries = tries + 1
		local meRoot = LocalPlayer.Character:FindFirstChild("HumanoidRootPart")
		if meRoot and (meRoot.Position - root.Position).Magnitude <= config.tradeDistance then
			log("✅ 已靠近目标")
			return true
		end
		wait(0.2)
	end
	log("❌ 无法靠近目标")
	return false
end

-- 装备指定槽位的物品
local function equipHotbar(slot)
	log("装备槽位 " .. slot)
	pcall(function()
		game:GetService("VirtualInputManager"):SendKeyEvent(true, Enum.KeyCode["One"].Value + (slot - 1), false, game)
		wait(0.05)
		game:GetService("VirtualInputManager"):SendKeyEvent(false, Enum.KeyCode["One"].Value + (slot - 1), false, game)
	end)
	wait(0.5) -- 等待装备完成
end

-- 获取当前装备的宠物信息
local function getCurrentPet()
	local character = LocalPlayer.Character
	if not character then return nil end

	-- 检查当前装备的工具
	local equippedTool = character:FindFirstChildOfClass("Tool")
	if equippedTool then
		log("当前装备的宠物: " .. equippedTool.Name)
		return equippedTool
	end

	-- 检查背包中的宠物
	local backpack = LocalPlayer:FindFirstChild("Backpack")
	if backpack then
		for _, tool in ipairs(backpack:GetChildren()) do
			if tool:IsA("Tool") then
				-- 检查是否是宠物工具
				local petNames = {"Lab", "Dog", "Cat", "Bird", "Pet", "Golden", "Dragon", "Fox", "Bee", "Butterfly", "Puppy", "Kitten"}
				for _, petName in ipairs(petNames) do
					if tool.Name:find(petName) then
						log("背包中找到宠物: " .. tool.Name)
						return tool
					end
				end
			end
		end
	end

	log("❌ 未找到宠物")
	return nil
end

-- 查找宠物赠送的 ProximityPrompt
local function findPetGiftPrompt(target)
	if not (target and target.Character) then return nil end
	local root = target.Character:FindFirstChild("HumanoidRootPart")
	if not root then return nil end

	log("搜索宠物赠送 ProximityPrompt...")
	
	local prompts = {}
	for _, d in ipairs(workspace:GetDescendants()) do
		if d:IsA("ProximityPrompt") then
			local ok, part = pcall(function() 
				return d.Parent and d.Parent:IsA("Attachment") and d.Parent.Parent or d.Parent 
			end)
			local anchor = part and part:FindFirstChild("Position") and part or (part and part:IsA("BasePart") and part or nil)
			local pos
			if anchor and anchor:IsA("BasePart") then pos = anchor.Position end
			if pos then
				local dist = (pos - root.Position).Magnitude
				if dist <= 15 then
					local actionText = tostring(d.ActionText):lower()
					log("发现提示: " .. actionText .. " (距离: " .. math.floor(dist) .. ")")
					
					-- 查找宠物相关的提示
					if actionText:match("gift") and actionText:match("pet") then
						table.insert(prompts, {
							prompt = d,
							distance = dist,
							actionText = actionText
						})
						log("✅ 找到宠物赠送提示: " .. actionText)
					end
				end
			end
		end
	end
	
	-- 按距离排序，选择最近的
	if #prompts > 0 then
		table.sort(prompts, function(a, b) return a.distance < b.distance end)
		return prompts[1].prompt
	end
	
	log("❌ 未找到宠物赠送提示")
	return nil
end

-- 触发 ProximityPrompt
local function firePrompt(prompt)
	if not prompt then return false end
	log("尝试触发宠物赠送提示: " .. tostring(prompt.ActionText))
	
	-- 优先使用 fireproximityprompt（若可用）
	if typeof(fireproximityprompt) == "function" then
		pcall(function()
			fireproximityprompt(prompt, prompt.HoldDuration + config.holdDurationPadding)
		end)
		log("✅ 使用 fireproximityprompt 触发")
		return true
	end
	
	-- 备用方法：使用 InputHold 模拟
	local ok = pcall(function()
		prompt:InputHoldBegin()
		wait((prompt.HoldDuration or 0) + config.holdDurationPadding)
		prompt:InputHoldEnd()
	end)
	
	if ok then
		log("✅ 使用 InputHold 触发")
	else
		log("❌ 触发失败")
	end
	
	return ok
end

-- 主要的宠物赠送功能
local function giftPetToTarget(targetPlayer)
	log("=== 开始宠物赠送 ===")
	
	if not targetPlayer then
		log("❌ 没有目标玩家")
		return false
	end

	log("目标玩家: " .. targetPlayer.Name)

	-- 检查是否有宠物
	local pet = getCurrentPet()
	if not pet then
		log("❌ 没有找到宠物，请确保背包中有宠物")
		return false
	end

	-- 靠近目标
	if not moveNear(targetPlayer) then
		log("❌ 无法靠近目标")
		return false
	end

	-- 装备宠物
	equipHotbar(config.petSlot)
	
	-- 等待一下让游戏识别装备的宠物
	wait(1)

	-- 查找并触发宠物赠送提示
	local prompt = findPetGiftPrompt(targetPlayer)
	if not prompt then
		log("❌ 未找到宠物赠送提示，请确保:")
		log("1. 目标玩家在线")
		log("2. 距离足够近")
		log("3. 已装备宠物")
		return false
	end

	-- 触发赠送
	if firePrompt(prompt) then
		log("✅ 宠物赠送触发成功！")
		log("请检查目标玩家是否收到 Accept/Decline 界面")
		return true
	else
		log("❌ 宠物赠送触发失败")
		return false
	end
end

-- 自动接受宠物赠送（接收端）
local function setupAutoAccept()
	if not config.autoAcceptOnReceiver then return end
	
	log("设置改进的自动接受功能...")
	
	local function findAcceptButton()
		local pg = LocalPlayer:FindFirstChild("PlayerGui")
		if not pg then return nil end
		
		-- 递归搜索所有UI元素
		local function searchUI(parent)
			for _, child in ipairs(parent:GetChildren()) do
				if child:IsA("GuiObject") then
					local name = child.Name:lower()
					local text = ""
					local className = child.ClassName
					
					-- 获取文本内容
					if child:IsA("TextLabel") or child:IsA("TextButton") then
						text = (child.Text or ""):lower()
					end
					
					-- 检查是否是接受按钮
					if (name:match("accept") or name:match("yes") or name:match("confirm") or 
						text:match("accept") or text:match("yes") or text:match("confirm")) and
						(child:IsA("TextButton") or child:IsA("ImageButton") or child:IsA("GuiButton")) then
						
						log("找到接受按钮: " .. child.Name .. " (" .. className .. ")")
						log("按钮文本: " .. tostring(child.Text))
						return child
					end
					
					-- 递归搜索子元素
					local found = searchUI(child)
					if found then return found end
				end
			end
			return nil
		end
		
		return searchUI(pg)
	end

	local function clickButton(btn)
		if not btn then return false end
		
		log("尝试点击按钮: " .. btn.Name)
		
		-- 方法1: 直接调用 Activated 事件
		local success = pcall(function()
			if btn.Activated then
				btn.Activated:Fire()
				log("✅ 使用 Activated 事件成功")
				return true
			end
		end)
		if success then return true end
		
		-- 方法2: 使用 Fire 方法
		success = pcall(function()
			btn:Fire("Activated")
			log("✅ 使用 Fire(Activated) 成功")
			return true
		end)
		if success then return true end
		
		-- 方法3: 模拟鼠标点击
		success = pcall(function()
			btn:Fire("MouseButton1Click")
			log("✅ 使用 MouseButton1Click 成功")
			return true
		end)
		if success then return true end
		
		-- 方法4: 模拟完整的鼠标交互
		success = pcall(function()
			btn:Fire("MouseEnter")
			wait(0.05)
			btn:Fire("MouseButton1Down")
			wait(0.05)
			btn:Fire("MouseButton1Up")
			btn:Fire("MouseLeave")
			log("✅ 使用完整鼠标交互成功")
			return true
		end)
		if success then return true end
		
		log("❌ 所有点击方法都失败")
		return false
	end

	-- 监听UI变化
	local playerGui = LocalPlayer:WaitForChild("PlayerGui")
	
	playerGui.ChildAdded:Connect(function()
		wait(0.1) -- 等待UI完全加载
		local btn = findAcceptButton()
		if btn then
			log("检测到新UI中的接受按钮")
			clickButton(btn)
		end
	end)
	
	playerGui.DescendantAdded:Connect(function(descendant)
		if descendant:IsA("TextButton") or descendant:IsA("ImageButton") then
			local name = descendant.Name:lower()
			local text = ""
			if descendant:IsA("TextButton") then
				text = (descendant.Text or ""):lower()
			end
			
			if name:match("accept") or name:match("yes") or text:match("accept") or text:match("yes") then
				log("检测到新的接受按钮: " .. descendant.Name)
				wait(0.1)
				clickButton(descendant)
			end
		end
	end)
	
	-- 定期检查
	spawn(function()
		while true do
			local btn = findAcceptButton()
			if btn then
				log("检测到接受按钮，尝试自动点击")
				clickButton(btn)
			end
			wait(0.5)
		end
	end)
end

-- 手动测试接受功能
local function testAccept()
	log("=== 手动测试接受功能 ===")
	local pg = LocalPlayer:FindFirstChild("PlayerGui")
	if not pg then 
		log("未找到 PlayerGui")
		return 
	end
	
	-- 递归搜索所有UI元素
	local function searchUI(parent, depth)
		depth = depth or 0
		local indent = string.rep("  ", depth)
		
		for _, child in ipairs(parent:GetChildren()) do
			if child:IsA("GuiObject") then
				local name = child.Name:lower()
				local text = ""
				local className = child.ClassName
				
				if child:IsA("TextLabel") or child:IsA("TextButton") then
					text = (child.Text or ""):lower()
				end
				
				log(indent .. child.Name .. " (" .. className .. ") - 文本: " .. tostring(child.Text))
				
				-- 检查是否是接受按钮
				if (name:match("accept") or name:match("yes") or name:match("confirm") or 
					text:match("accept") or text:match("yes") or text:match("confirm")) and
					(child:IsA("TextButton") or child:IsA("ImageButton") or child:IsA("GuiButton")) then
					
					log("🎯 找到接受按钮: " .. child.Name .. " (" .. className .. ")")
					log("按钮文本: " .. tostring(child.Text))
					log("按钮路径: " .. child:GetFullName())
					
					-- 尝试点击
					local success = pcall(function()
						if child.Activated then
							child.Activated:Fire()
							log("✅ 使用 Activated 事件成功")
						else
							child:Fire("Activated")
							log("✅ 使用 Fire(Activated) 成功")
						end
					end)
					
					if not success then
						log("❌ 点击失败")
					end
					
					return child
				end
				
				-- 递归搜索子元素
				local found = searchUI(child, depth + 1)
				if found then return found end
			end
		end
		return nil
	end
	
	local btn = searchUI(pg)
	if not btn then
		log("❌ 未找到接受按钮")
	end
end

-- 快捷键控制
UserInputService.InputBegan:Connect(function(input, gp)
	if gp then return end
	
	if input.KeyCode == Enum.KeyCode.P then
		-- 宠物赠送
		local target = getTarget()
		giftPetToTarget(target)
	elseif input.KeyCode == Enum.KeyCode.T then
		-- 测试模式：显示当前宠物信息
		local pet = getCurrentPet()
		if pet then
			log("当前宠物: " .. pet.Name)
		else
			log("未找到宠物")
		end
	elseif input.KeyCode == Enum.KeyCode.R then
		-- 重新装备宠物
		equipHotbar(config.petSlot)
		log("重新装备宠物到槽位 " .. config.petSlot)
	elseif input.KeyCode == Enum.KeyCode.A then
		-- 手动测试接受功能
		testAccept()
	end
end)

-- 创建控制UI
local function createControlUI()
	local screenGui = Instance.new("ScreenGui")
	screenGui.Name = "PetGiftControlUI"
	screenGui.ResetOnSpawn = false
	screenGui.Parent = LocalPlayer:WaitForChild("PlayerGui")
	
	local mainFrame = Instance.new("Frame")
	mainFrame.Name = "MainFrame"
	mainFrame.Size = UDim2.new(0, 300, 0, 200)
	mainFrame.Position = UDim2.new(0, 10, 0, 10)
	mainFrame.BackgroundColor3 = Color3.fromRGB(40, 40, 40)
	mainFrame.BorderSizePixel = 0
	mainFrame.Parent = screenGui
	
	local titleLabel = Instance.new("TextLabel")
	titleLabel.Name = "Title"
	titleLabel.Size = UDim2.new(1, 0, 0, 30)
	titleLabel.Text = "宠物赠送控制面板"
	titleLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
	titleLabel.TextScaled = true
	titleLabel.Font = Enum.Font.SourceSansBold
	titleLabel.BackgroundTransparency = 1
	titleLabel.Parent = mainFrame
	
	local giftButton = Instance.new("TextButton")
	giftButton.Name = "GiftButton"
	giftButton.Size = UDim2.new(0, 120, 0, 30)
	giftButton.Position = UDim2.new(0, 10, 0, 40)
	giftButton.Text = "赠送宠物 (P)"
	giftButton.TextColor3 = Color3.fromRGB(255, 255, 255)
	giftButton.TextScaled = true
	giftButton.Font = Enum.Font.SourceSans
	giftButton.BackgroundColor3 = Color3.fromRGB(70, 130, 70)
	giftButton.BorderSizePixel = 0
	giftButton.Parent = mainFrame
	
	local testButton = Instance.new("TextButton")
	testButton.Name = "TestButton"
	testButton.Size = UDim2.new(0, 120, 0, 30)
	testButton.Position = UDim2.new(0, 140, 0, 40)
	testButton.Text = "测试宠物 (T)"
	testButton.TextColor3 = Color3.fromRGB(255, 255, 255)
	testButton.TextScaled = true
	testButton.Font = Enum.Font.SourceSans
	testButton.BackgroundColor3 = Color3.fromRGB(130, 70, 70)
	testButton.BorderSizePixel = 0
	testButton.Parent = mainFrame
	
	local equipButton = Instance.new("TextButton")
	equipButton.Name = "EquipButton"
	equipButton.Size = UDim2.new(0, 120, 0, 30)
	equipButton.Position = UDim2.new(0, 10, 0, 80)
	equipButton.Text = "装备宠物 (R)"
	equipButton.TextColor3 = Color3.fromRGB(255, 255, 255)
	equipButton.TextScaled = true
	equipButton.Font = Enum.Font.SourceSans
	equipButton.BackgroundColor3 = Color3.fromRGB(70, 70, 130)
	equipButton.BorderSizePixel = 0
	equipButton.Parent = mainFrame
	
	local closeButton = Instance.new("TextButton")
	closeButton.Name = "CloseButton"
	closeButton.Size = UDim2.new(0, 30, 0, 30)
	closeButton.Position = UDim2.new(1, -40, 0, 10)
	closeButton.Text = "X"
	closeButton.TextColor3 = Color3.fromRGB(255, 255, 255)
	closeButton.TextScaled = true
	closeButton.Font = Enum.Font.SourceSansBold
	closeButton.BackgroundColor3 = Color3.fromRGB(80, 80, 80)
	closeButton.BorderSizePixel = 0
	closeButton.Parent = mainFrame
	
	local statusLabel = Instance.new("TextLabel")
	statusLabel.Name = "Status"
	statusLabel.Size = UDim2.new(1, -20, 0, 80)
	statusLabel.Position = UDim2.new(0, 10, 0, 120)
	statusLabel.Text = "状态: 就绪\n目标: " .. config.targetPlayer .. "\n宠物槽位: " .. config.petSlot .. "\n按 P 键赠送宠物"
	statusLabel.TextColor3 = Color3.fromRGB(200, 200, 200)
	statusLabel.TextScaled = true
	statusLabel.Font = Enum.Font.SourceSans
	statusLabel.BackgroundTransparency = 1
	statusLabel.Parent = mainFrame
	
	giftButton.MouseButton1Click:Connect(function()
		local target = getTarget()
		giftPetToTarget(target)
	end)
	
	testButton.MouseButton1Click:Connect(function()
		local pet = getCurrentPet()
		if pet then
			statusLabel.Text = "当前宠物: " .. pet.Name
		else
			statusLabel.Text = "未找到宠物"
		end
	end)
	
	equipButton.MouseButton1Click:Connect(function()
		equipHotbar(config.petSlot)
		statusLabel.Text = "已装备槽位 " .. config.petSlot
	end)
	
	closeButton.MouseButton1Click:Connect(function()
		screenGui:Destroy()
	end)
	
	return screenGui
end

-- 启动
log("自动宠物赠送系统已启动")
log("目标玩家: " .. config.targetPlayer)
log("宠物槽位: " .. config.petSlot)

-- 设置自动接受
setupAutoAccept()

-- 创建控制UI
createControlUI()

log("快捷键:")
log("P - 赠送宠物")
log("T - 测试当前宠物")
log("R - 重新装备宠物")
log("A - 手动测试接受功能")
